package routers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"

	/*"strconv"
	"timemaker/models"*/

	"git.oschina.net/fanbuchi/timemaker/models"
	"github.com/astaxie/beego/logs"
	"strconv"
)

//过滤器
//参数过滤 ？ 放在controller中使用？
//非法字符过滤
//请求路径过滤
//权限验证过滤

var timelog = logs.NewLogger(20000)

func init() {
	timelog.SetLogger("file", `{"filename":"logs/router.log"}`)

	var FilterAuth = func(ctx *context.Context) {
		client_id := ctx.Input.Header("client_id")
		bear := ctx.Input.Header("bear")
		if client_id == "" {
			authError := "{\"status\":" + strconv.Itoa(models.AuthorizeError) + "," + "\"desc\":\"参数client_id不能为空\"}"
			ctx.ResponseWriter.Write([]byte(authError))
			return
		}
		if bear == "" {
			err := models.ValidClientDetails(client_id, "")
			if err != nil {
				authError := "{\"status\":" + strconv.Itoa(models.AuthorizeError) + "," + "\"desc\":\"" + err.Error() + "\"}"
				ctx.ResponseWriter.Write([]byte(authError))
				return
			}
		}

	}

	var routerLog = func(ctx *context.Context) {

	}

	var requestRouterLog = func(ctx *context.Context) {
		//ctx.Request.RemoteAddr
		timelog.Info(ctx.Request.URL.String(), ctx.Request.Header.Get("X-Forwarded-For"))
	}

	beego.InsertFilter("/v1/*", beego.BeforeRouter, requestRouterLog)
	beego.InsertFilter("/v1/*", beego.BeforeRouter, FilterAuth)
	beego.InsertFilter("/v1/*", beego.FinishRouter, routerLog)

	/*var FilterUser = func(ctx *context.Context) {
		_, ok := ctx.Input.Session("uid").(int)
		if !ok && ctx.Request.RequestURI != "/login" {
			ctx.WriteString("登陆")
		}
	}
	beego.InsertFilter("/api*/ /*",beego.BeforeRouter,FilterUser)*/

	/*var UrlManager = func(ctx *context.Context) {
		//数据库读取全部的url mapping数据
		urlMapping := model.GetUrlMapping()
		for baseurl,rule:=range urlMapping {
			if baseurl == ctx.Request.RequestURI {
				ctx.Input.RunController = rule.controller
				ctx.Input.RunMethod = rule.method
				break
			}
		}
	}

	beego.InsertFilter("*/ /*",beego.BeforeRouter,UrlManager)*/

}
